﻿/*  
 *  IIS LogFile Analyser, Copyright (C) 2013. http://www.iis-analyser.com
 *  --
 *  This program is free software, provided "AS IS" WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
 * 
 *  File Author: Ian Quigley,    2013-02-23
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Script.Serialization;
using Web.Common;

namespace Web.Filter
{
    public class FilterSite : IFilterView
    {
        public string Name
        {
            get { return "Site Filter"; }
        }

        public void BuildHtml(StringBuilder html, string sqlColumn)
        {
            var store = BasePage.GetDataStore();

            if (store.Sites.Count() <= 1)
                return ;

            html.Append( "<td align='right' width='20%'><b>Sites</b></td><td width='80%'><div id='siteFilter' class='multiselect' data-sqlcolumn='" + sqlColumn + "' data-filtertype='FilterSite'><div data-item='all' selected='selected'>All</div>" );
            foreach (var site in store.Sites)
            {
                html.AppendFormat( "<div data-item='{0}'>{1}</div>", site.Id, site.Name );
            }
            html.Append( "</div></td>" );            
        }

        public string UpdateSql( string sql, FilterItem item )
        {
            var jsonSerialize = new JavaScriptSerializer();
            string replace;

            List<string> siteIds = jsonSerialize.Deserialize<List<String>>( item.Data );
            if (!siteIds.Any())
                replace = "(1=1) ";
            else
                replace = string.Format( "{0} in ({1}) ", item.SqlColumn, string.Join( ", ", siteIds ) );
    
            return sql.Replace( "{" + item.SqlColumn + "}", replace, StringComparison.OrdinalIgnoreCase );
        }

    }
}